﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Routing;

namespace RestUpMVC.Resource
{
    internal class ResourceRouteBuilder
    {
        public RouteBase[] BuildRoutes(string baseUri, ResourceMetaData metaData, bool addResourceNameToUri)
        {
            if (baseUri == null) throw new ArgumentNullException("baseUri");
            if (metaData == null) throw new ArgumentNullException("metaData");

            string resourceBaseUri = addResourceNameToUri ? string.Format("{0}/{1}", baseUri, metaData.Name) : baseUri;
            string resourceFullUri = resourceBaseUri + "/{" + metaData.IdentityPropertyName + "}";

            var routes = new List<RouteBase>();

            string controllerTypeName = metaData.ControllerType.Name;
            string controllerName = controllerTypeName.Remove( controllerTypeName.LastIndexOf("controller", StringComparison.OrdinalIgnoreCase));
            if (metaData.AllowList)
            {
                routes.Add(BuildRoute(resourceBaseUri, "list", controllerName, "GET"));
            }

            if (metaData.AllowGet)
            {
                routes.Add(BuildRoute(resourceFullUri, "get", controllerName, "GET"));
            }

            if (metaData.AllowDelete)
            {
                routes.Add(BuildRoute(resourceFullUri, "delete", controllerName, "DELETE"));
            }

            if (metaData.AllowPost)
            {
                routes.Add(BuildRoute(resourceBaseUri, "post", controllerName, "POST"));
            }

            if (metaData.AllowPut)
            {
                routes.Add(BuildRoute(resourceFullUri, "put", controllerName, "PUT"));
            }

            return routes.ToArray();
        }

        private static RouteBase BuildRoute(string uri, string action, string controller, string methodConstraint)
        {
            return new Route(uri, new MvcRouteHandler())
                       {
                           Defaults = new RouteValueDictionary(new {action, controller}),
                           Constraints = new RouteValueDictionary(new {httpMethod = new HttpMethodConstraint(methodConstraint)})
                       };
        }
    }
}